layui.define(["jquery"], function (exports) {
    "use strict";

    var $ = layui.$;
    let observer;

    var jmImg = {
        /**
         * 图片加载优化开启
         * @param {String} load 
         */
        start: function (load) {
            layui.img(load, function () {
                fun(load)
                // 创建一个观察器实例
                observer = new MutationObserver((mutationsList, observer) => {
                    for (let mutation of mutationsList) {
                        if (mutation.type === 'childList') {
                            fun(load)
                        }
                    }
                });

                // 配置观察选项
                const config = { childList: true, subtree: true };

                // 传入目标节点和观察选项
                observer.observe(document.body, config);
            });
        },
        /**
         * 图片加载优化关闭
         */
        stop: function () {
            observer.disconnect();
        }
    }

    var fun = function (load) {
        for (let i = 0; i < $("img").length; i++) {
            var isImg = $("img")[i];
            var newSrc = isImg.getAttribute("jm-src"); //要显示的图片地址
            if (newSrc !== null && newSrc != "" && newSrc != load) {
                isImg.src = load; //加载中的图片地址
                var img = new Image();
                img.src = newSrc;
                img.onload = function () {
                    $("img")[i].src = this.src
                }
            } else {
                continue;
            }
        }
    }

    exports('jmImg', jmImg); // 输出模块
});  